from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from classdata import *
import json
import pathlib
import logging
import time
import socket
import os,sys
import pymysql
import sqlite3
import loger
import random
log = loger.Logger('enaea.edu.cn',StreamLevel='info',FileLevel='info').logger
# chrome.exe --remote-debugging-port=9222 --user-data-dir=D:\selenium_chrome

root=pathlib.Path(os.path.dirname(os.path.realpath(sys.argv[0])))

print(root)
chromeOpitons = Options()
Rate=1
log.debug("start")
def init():
    global browser
    chrome_options = Options()
    # chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    chrome_options.add_argument("--ignore-certificate-errors")
    chrome_options.binary_location=r"D:\chrome-win64\chrome.exe"
    service=Service(str(root/"chromedriver.exe"))
    browser = webdriver.Chrome(service=service, options=chrome_options)
    # browser = webdriver.Chrome(options=chrome_options)
    browser.maximize_window()
    browser.implicitly_wait(15)
    return browser



def findElementByText(text):
    obj=None
    try:
        obj=browser.find_element(By.LINK_TEXT,text)
    except:
        log.debug(f"{text} not find")
        return False
    else:
        log.debug(f"find {text}")
        return obj
def findElementByXpath(xpath):
    obj=None
    try:
        obj=browser.find_element(By.XPATH,xpath)
    except:
        log.debug(f"not find xpath: {xpath}")
        return False
    else:
        return obj
def tryfind(str):
    obj = None
    try :

        obj=browser.find_element(By.XPATH,str)
        log.debug(obj.text)
        f='//*[@id="J_myOptionRecords"]'
        chp = browser.find_element(By.XPATH,f + "/descendant::a")
        chp[3].click()
        log.debug(chp[0].text)
    except :
        log.debug(f"未找到{str}")
        return False
    finally :
        return obj

def tryclick(xpath):
    try:
        browser.find_element(By.XPATH,xpath).click()
    except:
        log.debug(f"点击失败:{xpath}")
        return False
    else:
        log.debug(f"点击成功:{xpath}")
        return True

def tjs(js):
    try:
        obj = browser.execute_script(js)
    except:
        log.debug(f"执行失败:{js}")
        return False
    else:
        log.debug(f"执行成功:{js}")
        return obj

def switch2nowPage():

    handles = browser.window_handles
    try:
        browser.switch_to_window(handles[len(handles)-1])
        # browser.switch_to.window(handles[0])
        # browser.switch_to.window(browser.current_window_handle)
    except Exception as e:
        log.exception(e)
        log.error('switch_to_window error!')


# def getlist1():
#     totalCount=1
#     start=0
#     mylist1=[]
#     # https://study.enaea.edu.cn/circleIndex.do?action=getMyClass&start=0&limit=20&isCompleted=false&circleId=173288&syllabusId=1043229&categoryRemark=all&_=1669954685801&_=1669954685801
#     # while(start<totalCount):
#     #     js= f"list1=$.get(\"https://study.enaea.edu.cn/circleIndex.do?action=getMyClass&start={start}&limit=20&isCompleted=&circleId=173288&syllabusId=1043229&categoryRemark=all&_={int(time.time())}\");"  
#     #     start=start+20
#     #     jsobj=tjs(js)
#     #     js= f"return list1.responseText;"  
#     #     time.sleep(0.2)
#     #     jsobj=tjs(js)
#     #     jsonlist=demjson.decode(jsobj)
#     #     totalCount=jsonlist['totalCount']

#     #     for i in jsonlist["result"]["list"]:
#     #         log.debug(f"{i['studyCenterDTO']['courseId']}:{i['studyCenterDTO']['studyProgress']}%")
#     #         mylist1.append((i['studyCenterDTO']['courseId'],i['studyCenterDTO']['studyProgress']))
#     #     if(int(mylist1[-1][1])==0) :return mylist1
#     jsonlist=getjson(f"https://study.enaea.edu.cn/circleIndex.do?action=getMyClass&start=0&limit=20&isCompleted=false&circleId=173288&syllabusId=1043229&categoryRemark=all&_={int(time.time())}")
#     for i in jsonlist["result"]["list"]:
#         log.debug(f"{i['studyCenterDTO']['courseId']}:{i['studyCenterDTO']['studyProgress']}%")
#         mylist1.append((i['studyCenterDTO']['courseId'],i['studyCenterDTO']['studyProgress']))
#     return mylist1

# def play1(list):

#     for i in list:
#         if(i[1]!='100'):
#             id=i[0]
#             tjs(f"window.open(\"https://study.enaea.edu.cn/viewerforccvideo.do?courseId={id}&circleId=173288\")")
#             time.sleep(0.5)
#             switch2nowPage()
#             url=f"https://study.enaea.edu.cn/course.do?action=getCourseContentList&courseId={id}&circleId=173288&_={int(time.time())}"
#             list2=getjson(url)
#             return list2
#             break
# def play2(list):
#     tryclick('//*[@id="J_CC_videoPlayerDiv"]/xg-start/div[1]')
#     # tryclick('/html/body/div[9]/table/tbody/tr[2]/td[2]/div[3]/button')
#     if(tjs("document.getElementsByTagName('button')[0].click();")!=False):
#         log.info("20分钟点击")
#     # J_studyProgress_57997
#     temp=[]
#     try:
#         for i in list["result"]["list"]:
#             xpath=f"//*[@id=\"J_studyProgress_{i['id']}\"]"
#             obj=findxpath(xpath)
#             xpath1=f"//*[@id=\"J_cvtb_course_content_{i['id']}\"]"
#             obj1=findxpath(xpath1)
#             temp.append((i['id'],obj.text,obj1.get_attribute('class')))
#             # if(obj.text!="100%"): 
#             #     log.debug(f"{i['id']}:{obj.text}")
#             #     falg=True
#         f1=True
#         for i in temp:
#             if(i[1]!="100%"): 
#                 f1=False
#                 log.debug(f"------{i[0]}:{i[1]}")
#             log.debug(f"{i[0]}:{i[1]}\t{i[2]}")
#         if (f1):
#             tjs('window.close();')
#             switch2nowPage()
#         time.sleep(0.1)
#     except Exception as e :
#         log.exception(e)

def getjson(url):
    try:
        js= f"mytemp=$.get(\"{url}\");"  
        jsobj=tjs(js)
        js= f"return mytemp.responseText;"  
        time.sleep(0.2)
        jsobj=tjs(js)
        return jsobj
    except Exception as e :
        log.error(f"getjson error:{url}")
        log.exception(e)
def switch2url(url):
        handles=browser.window_handles
        for i in handles:
            browser.switch_to.window(i)
            log.debug(browser.current_url[0:len(url)])
            if(browser.current_url[0:len(url)]==url):
                return True
                break
        return False
def switchPlay():
    pass
def play():
    switch2url("https://study.enaea.edu.cn/viewerforccvideo.do")
    tjs("p = document.getElementsByClassName('cvtb-MCK-CsCt-studyProgress');")
    tjs("tit = document.getElementsByClassName('cvtb-MCK-CsCt-title');")
    tjs("video_=document.querySelector('video')")
    tjs(f"document.querySelector('video').playbackRate={Rate};")
    l=tjs("return p.length")
    nowplay=0
    time_=0
    t1=0
    pas1=""
    while True:
        log.debug(browser.current_url)
        if(tjs("document.getElementsByTagName('button')[0].click();")!=False):
            log.info("20分钟点击")
        tjs("document.querySelector('video').play();")
        tjs(f"document.querySelector('video').playbackRate={Rate};")
        tjs("document.querySelector('video').volume=0.01;")
        fl_=True
        for i in range(l):
            pas=tjs(f"return  p[{i}].innerText;")
            if( pas !="100%"):
                fl_=False
                break
        if(i != nowplay ):
            nowplay=i
            tit=tjs(f"return tit[{i}].innerText")
            log.info(f"{userinfo[2]} 正在播放：({pas}) {tit} ")
            tjs(f"p[{i}].click();")
            t1=0
        if(fl_):
            time.sleep(15)
            log.info("完成")
            tjs("window.close();")
            return True
        else:
            tit=tjs(f"return tit[{i}].innerText")
            if(tit==False):
                log.error("异常退出")
                tjs("window.close();")
                return False
            if(pas==pas1):
                t1=t1+1
                print(f" {userinfo[2]} 正在观看：({pas}) {tit}   {t1}                          ")
                if(t1>20):
                    log.error("播放异常")
                    tjs("window.close();")
                    return False
            else:
                pas1=pas
                t1=0
            print(f" {userinfo[2]} 正在观看：({pas}) {tit}   ")
        time.sleep(15)
        time_+=1
        log.debug(time_)
        if(time_>=4*120):
            time_=0
            tjs("window.close();")
            time.sleep(3)
            return True


def getUserList():
    with open(root/"enaea.userinfo.txt",encoding='GBK') as f:
        i=f.read()
        log.debug(i)
        userinfolist=eval(i)
    return userinfolist
def getAccount():
    global Rate
    userAccount=input("账号:")
    if(userAccount==""):
        ul=getUserList()
        for i in ul:
            print(f"{ul.index(i)}:{i}")
        i=int(input())
        Rate=input("播放倍率:")
        return [ul[i][1],ul[i][2]]
    else:
        userPass=input("密码:")
        Rate=input("播放倍率:")
        return [userAccount,userPass]

def login(userinfo):
    time.sleep(1)
    handles=browser.window_handles
    browser.switch_to.window(handles[0])
    browser.get("https://study.enaea.edu.cn/login.do")
    time.sleep(1)
    iu=findElementByXpath("/html/body/div[2]/div/div/div/form/div[1]/div[2]/div[1]/div[1]/input")
    ip=findElementByXpath("/html/body/div[2]/div/div/div/form/div[1]/div[2]/div[1]/div[2]/input")
    iu.send_keys(userinfo[0])
    time.sleep(1)
    ip.send_keys(userinfo[1])
    time.sleep(1)
    b=findElementByXpath("/html/body/div[2]/div/div/div/form/div[1]/div[2]/div[1]/div[4]/button")
    b.click()
    time.sleep(2)
    ui=findElementByXpath("/html/body/div[2]/div[2]/div/div[2]/div/span/a")
    username=ui.text
    userinfo=userinfo[0:2]
    userinfo.append(username)
    return userinfo
def step1():
    p=findElementByXpath("/html/body/div[2]/div[7]/div[2]/div/div[2]/div/div[2]/div/div[3]/p[1]/a")
    p.click()
    time.sleep(3)
    switch2url("https://study.enaea.edu.cn/circleIndexRedirect.do?action=toCircleIndex")
    p=findElementByXpath("/html/body/div[4]/div[2]/div[2]/div/div[2]/a")
    urllist=p.get_attribute("href")
    p.click()
    return urllist
def logout():
    browser.get("https://passport.enaea.edu.cn/logout.do")
if __name__ == "__main__" :
    userinfo=getAccount()
    browser=init()
    userinfo=login(userinfo)
    urllist=step1()
    # switch2nowPage()


    
    
    while True:
        if(not switch2url("https://study.enaea.edu.cn/viewerforccvideo.do")):
            browser.get(urllist)
        else:
            browser.refresh()
        time.sleep(5)
        if(tryclick("/html/body/div[4]/div[2]/div/div/ul/li[2]/span") == False):
            browser.refresh()
            time.sleep(5)
            f_= tjs("return document.getElementsByClassName('form-item-psw')[0].textContent")
            if(f_=="密码登录"):
                for i in range(30,0,-1):
                    print(f"  等待重新登录 {i}    ")
                    time.sleep(1)
                tjs('window.close();')
                login(userinfo)
                urllist=step1()
                log.info(f"重新登录{userinfo[2]}:{userinfo[0]}")
                continue

        time.sleep(3)
        tryclick("/html/body/div[4]/div[2]/div/div/div[3]/div/table/tbody/tr[2]/td[6]/a")
        time.sleep(3)
        play()

    # tjs('window.close();')


'''
time.sleep(1)
loadCookie()  
time.sleep(1)   
browser.get('http://study.enaea.edu.cn')
time.sleep(1)
'''
# https://study.enaea.edu.cn/course.do?action=getCourseContentList&courseId=296345&circleId=173288&_=1669901686898
# https://study.enaea.edu.cn/course.do?action=getCourseContentList&courseId=293830&circleId=173288&_=1669901414189
# https://study.enaea.edu.cn/course.do?action=getCourseContentList&courseId=293830&circleId=173288&_=1669900250
#             
# 
# 
# 
#                                                               276088605                 utc
# https://study.enaea.edu.cn/circleIndex.do?action=getMyClass&start=0&limit=20&isCompleted=&circleId=173288&syllabusId=1043229&categoryRemark=all&_=1669901784682&_=1669901784682
# ["result"]["list"]    ['studyCenterDTO']['courseId']
#                       ['studyCenterDTO']['studyProgress']

# https://study.enaea.edu.cn/circleIndexRedirect.do?action=toNewMyClass&type=course&circleId=226784&syllabusId=1362995&isRequired=true&studentProgress=100
# https://study.enaea.edu.cn/circleIndexRedirect.do?action=toNewMyClass&type=course&circleId=226784&syllabusId=1362995&isRequired=true&studentProgress=100
# https://study.enaea.edu.cn/circleIndexRedirect.do?action=toNewMyClass&type=course&circleId=226784&syllabusId=1362995&isRequired=true&studentProgress=100